package com.ck.async.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ck.async.mapper.StudentMapper;
import com.ck.async.service.AsyncTestService;
import com.ck.common.entity.SourceEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.concurrent.CountDownLatch;

/**
 * @author ck
 * @date 2023/11/17 10:21
 */
@Service
@Slf4j
public class AsyncTestServiceImpl extends ServiceImpl<StudentMapper,SourceEntity> implements AsyncTestService {

    @Autowired
    StudentMapper studentMapper;

    @Override
    @Async("asyncServiceExecutor")
    @Transactional
    public void executeAsync(List<SourceEntity> students, CountDownLatch countDownLatch) {
        try {
            log.info("start executeAsync");
            //异步线程要做的事情
            studentMapper.executeInsertBatch(students);
            log.info("end executeAsync");
        }catch (Exception e){
            e.printStackTrace();
        }
        finally {
            // 很关键, 无论上面程序是否异常必须执行countDown,否则await无法释放
            //对计数器进行递减1操作，当计数器递减至0时，当前线程会去唤醒阻塞队列里的所有线程。
            countDownLatch.countDown();
        }
    }
}
